package br.com.gsa.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;

//import org.ajax4jsf.framework.util.*;
import org.apache.commons.lang.StringUtils;

public class ComboboxConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
		if (StringUtils.isNotBlank(value)) {
			value = value.trim();
			if (value.length() > 0) {
				List<SelectItem> selectItems = null;//= SelectUtils.getSelectItems(arg0, arg1);
				ICombobox comboBox = null;
				for (SelectItem selectItem : selectItems) {
					if (selectItem.getValue() instanceof ICombobox) {
						comboBox = (ICombobox) selectItem.getValue();
					}
					if (comboBox.getValue().toString().replaceAll("\\s+", " ").equals(value.replaceAll("\\s+", " "))) {
						return comboBox;
					}
				}
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
		if (value == null) {
			return "";
		}
		if (value instanceof ICombobox) {
			Object value2 = ((ICombobox) value).getValue();
			if (value2 != null) {
				value2 = value2.toString().replaceAll("\\s+", " ");
				return value2.toString();
			}
		}
		return "";
	}

}
